package emp.config;

import emp.entity.PageInfo;
import emp.entity.SearchCriteria;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class PaginationService<T> {

    private static DataSourceConfig dataSourceConfig;

    private JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceConfig.dataSource());

    public PageInfo<T> getPage(String baseSql, SearchCriteria criteria, RowMapper<T> rowMapper, int pageNumber, int pageSize) {
        // 动态构建查询条件
        StringBuilder sqlBuilder = new StringBuilder(baseSql);
        List<Object> params = new ArrayList<>();

        // 添加查询条件
        if (criteria.getEducation() != null && !criteria.getEducation().equals("")) {
            sqlBuilder.append(" AND edu_id = ?");
            params.add(criteria.getEducation());
        }
        if (criteria.getJobNumber() != null && !criteria.getJobNumber().equals("")) {
            sqlBuilder.append(" AND emp_id = ?");
            params.add(criteria.getJobNumber());
        }
        if (criteria.getName() != null && !criteria.getName().equals("") ) {
            sqlBuilder.append(" AND emp_name LIKE ?");
            params.add("%" + criteria.getName() + "%"); // 姓名模糊查询
        }
        if (criteria.getHometown() != null && !criteria.getHometown().equals("")) {
            sqlBuilder.append(" AND hometown LIKE ?");
            params.add("%" + criteria.getHometown() + "%"); // 籍贯模糊查询
        }

        // 计算偏移量
        int offset = (pageNumber - 1) * pageSize;

        // 添加分页条件
        String paginatedSql = sqlBuilder.append(" LIMIT ? OFFSET ?").toString();
        params.add(pageSize);
        params.add(offset);

        // 查询当前页数据
        List<T> content = jdbcTemplate.query(paginatedSql, params.toArray(), rowMapper);

        // 查询总记录数（不考虑分页）
        String countSql = "SELECT COUNT(*) FROM (" + sqlBuilder.toString() + ") AS total";
        int totalRecords = jdbcTemplate.queryForObject(countSql, params.toArray(), Integer.class);

        // 封装分页信息
        return new PageInfo<>(pageNumber, pageSize, totalRecords, content);
    }


}
